﻿using System.Collections.Generic;
using System.Linq;
using SpreadsheetGear;

namespace MachiningHelper.ToolFile
{
    class ToolfileCheck
    {
        protected List<Tool> Tools { get; set; }
        public List<error> result { get; protected set; }

        public ToolfileCheck(string toolfile, MachiningPart part)
        {
            this.Tools = new List<Tool>();
            this.result = new List<error>();

            LoadTool(toolfile);
            check(part);
        }
        private void check(MachiningPart part)
        {
            var vdrills = part.Vdirlls;
            var hdrils = part.Hdrills;
            var routes = part.Routes;
            var saws = part.Saws;
            var nests = part.Nests;
            var vt = Tools.Where(it => it.ToolType == ToolType.VDrillX || it.ToolType == ToolType.VDrillY).ToList();
            var ht = Tools.Where(it => it.ToolType == ToolType.HDrill).ToList();
            var rt = Tools.Where(it => it.ToolType == ToolType.Route).ToList();
            var st = Tools.Where(it => it.ToolType == ToolType.Saw).ToList();

            foreach (var v in vdrills)
            {
                if (!vt.Exists(it => it.Diameter == double.Parse(v.VDrillDiameter)))
                    this.result.Add(error.垂直钻缺失);
            }
            foreach (var h in hdrils)
            {
                if (!ht.Exists(it => it.Diameter == double.Parse(h.HDrillDiameter)))
                    this.result.Add(error.水平钻缺失);
            }
            foreach (var r in routes)
            {
                if (!rt.Exists(it => it.Diameter == double.Parse(r.SetMillSeq.RouteDiameter)))
                    this.result.Add(error.铣刀缺失);
            }
            foreach (var s in saws)
            {
                if (!st.Exists(it => it.ToolName == s.SawToolName))
                    this.result.Add(error.锯片缺失);
            }
            foreach (var n in nests)
            {
                if (!rt.Exists(it => it.Diameter == double.Parse(n.SetMillSeq.RouteDiameter)))
                    this.result.Add(error.铣刀缺失);
            }

        }
        private void LoadTool(string toolfile)
        {
            IWorkbook book = Factory.GetWorkbook(toolfile);
            IWorksheet toolsheet = book.Worksheets["Tools"];
            IRange T = toolsheet.UsedRange;
            for (int i = 0; i < T.RowCount; i++)
            {
                if (string.IsNullOrEmpty(T[i, 0].Text))
                    break;
                var tool = new Tool
                  {
                      ToolName = T[i, 0].Text,
                      ToolType = (ToolType)(int.Parse(T[i, 8].Text)),
                      Diameter = (double)(T[i, 2].Value),
                      FeedSpeed = (double)(T[i, 5].Value)
                  };
                Tools.Add(tool);
            }
        }
       public enum error
        {
            垂直钻缺失 = 1,
            水平钻缺失 = 2,
            铣刀缺失 = 3,
            锯片缺失 = 4
        }
    }
}
